'use strict';
var 
    fs =require('fs'),
    url =require('url'),
    path =require('path'),
    http =require('http');

//从命令行参数获取root目录，默认是当前目录
var root =path.resolve(process.argv[2] || '.');
console.log('Static root dir: ' + root);
//创建服务器
var server = http.createServer(function(request,response){
    //或得url的path，类似'/css/bootstrap.css'
    var pathname = url.parse(request.url).pathname;
    console.log('pathname : ' + pathname);
    //获取对应的本地文件路径，类似'/srv/xxx/css/bootstrap.css'
    var filepath = path.join(root , pathname);
    console.log('filepath : ' + filepath);
    //获取文件状态
    fs.stat(filepath,function(err,stats){
        if(err){
            //出错了或文件不存在
            console.log('404 '+request.url);
            failure(response,'<h1>404 Not Found</h1>')
        }else{
            if(stats.isFile()){
                //没有出错并且是文件存在
                console.log('200 ' + request.url);
                sucess(response,filepath);
            }else{
                //文件夹
                console.log('200 ' + request.url);
                isDir(response,filepath); 
            }
        }       
    });

});

server.listen(8080);

console.log('Server is running at http://127.0.0.1:8080/');

function isDir(response,dir){
    fs.readdir(dir,function(err,files){
        if(err){
            failure(response,'<h1>404 该目录不存在</h1>');
        }else{
            console.log('files : '+files);
            var names = files.filter(function(file){
                return file === 'index.html' || file === 'default.html'
            });
            if(names.length !=0){
                var index = 0;
                if(names.length == 2){
                    index =1;
                }
                sucess(response,path.join(dir,names[index]));                    
            }else{
                failure(response,'<h1>404 不存在默认首页</h1>');
            }
        }
    });
}

function sucess(response , filepath){
        //发送200响应
        response.writeHead(200);
        //将文件流导向response
        fs.createReadStream(filepath).pipe(response);
}

function failure(response , errString){
        //发送404响应
        response.writeHead(404);
        response.end(errString);
}